<template>
  <div class="container tank-register">
    <div class="img-logo"></div>
    <div class="center">
      <Form
        :class="{ 'register-form': true, registered: isRegistered }"
        :rules="ruleCustom"
        ref="formValidate"
        :model="formValidate"
      >
        <div v-if="isRegistered" class="registered-info">
          <div class="tip">报名成功</div>
          <div class="team-name">{{ formValidate.teamName }}</div>
        </div>
        <FormItem v-show="!isRegistered" prop="teamName">
          <a
            href="https://sohu1024.bjcnc.scs.sohucs.com/game/maingame.zip"
            class="download-link blink_me"
            >点击下载游戏资源包</a
          >
          <Input
            class="input-name"
            v-model="formValidate.teamName"
            maxlength="30"
            placeholder="请输入队伍名称"
          />
        </FormItem>
        <div class="battle-file">
          <FormItem class="input-player" prop="playerAFileName">
            <input type="file" ref="playerAFile" @change="changeplayerAFile" />
            <div class="add">
              <div class="add-icon"></div>
              <div class="text">
                {{
                  isRegistered || formValidate.playerAFileName
                    ? "上传更新"
                    : "上传添加"
                }}
              </div>
            </div>
            <div class="file-name">
              A战队文件 {{ formValidate.playerAFileName }}
            </div>
          </FormItem>
          <FormItem class="input-player" prop="playerBFileName">
            <input type="file" ref="playerBFile" @change="changeplayerBFile" />
            <div class="add">
              <div class="add-icon"></div>
              <div class="text">
                {{
                  isRegistered || formValidate.playerBFileName
                    ? "上传更新"
                    : "上传添加"
                }}
              </div>
            </div>
            <div class="file-name">
              B战队文件 {{ formValidate.playerBFileName }}
            </div>
          </FormItem>
        </div>
        <div
          class="option-box"
          :class="{ 'option-box-isRegistered': isRegistered }"
        >
          <div class="select-group" v-if="!isRegistered">
            <div class="option-name">请选择队伍：</div>
            <RadioGroup v-model="formValidate.group">
              <Radio label="A" size="large">A组 (AI RANK)</Radio>
              <Radio label="B" size="large">B组 (车轮战)</Radio>
            </RadioGroup>
          </div>
          <div class="obscure">
            <div class="option-name">是否混淆代码：</div>
            <i-switch
              v-model="isObscure"
              size="small"
              @on-change="handleSwitchChange"
            ></i-switch>
          </div>
        </div>
        <div class="reg-btns">
          <Button
            v-if="!isRegistered"
            class="btn register-submit"
            type="primary"
            @click.prevent.stop="registerSubmit('formValidate')"
            >提交
          </Button>
          <Button
            v-if="isRegistered"
            class="btn update-file"
            type="primary"
            @click.prevent.stop="updateFile('formValidate')"
            >更新文件
          </Button>
          <!-- <Button v-if="isRegistered" class="btn cancle-register" type="primary"
            @click.prevent.stop="cancleRegister">取消报名
          </Button> -->
        </div>
      </Form>
      <div class="map-entrance" @click="toMapPage"></div>
    </div>
  </div>
</template>
<script>
import { Form, FormItem, Input, RadioGroup, Radio, Switch } from "view-design";
import JavaScriptObfuscator from "javascript-obfuscator";
import {
  getGameInfo,
  registerGame,
  cancleRegisterGame,
  updatePlayerFile,
} from "./utils/request";
import { getSSOTokenInfo } from "@/views/Tank/utils/index.js";

export default {
  components: {
    Form,
    FormItem,
    Input,
    RadioGroup,
    Radio,
    iSwitch: Switch,
  },
  mounted() {
    const userInfo = getSSOTokenInfo();
    this.userInfo = userInfo;
    this.init();
  },
  data() {
    const teamNameRule = (rule, value, callback) => {
      if (value.trim() === "") {
        this.$toast.center("请输入队名");
        return callback(new Error(""));
      }
      callback();
    };
    const playerAFileNameRule = (rule, value, callback) => {
      if (value.trim() === "") {
        this.$toast.center("请上传A战队文件");
        return callback(new Error(""));
      }
      callback();
    };
    const playerBFileNameRule = (rule, value, callback) => {
      if (value.trim() === "") {
        this.$toast.center("请上传B战队文件");
        return callback(new Error(""));
      }
      callback();
    };

    return {
      userInfo: {},
      isRegistered: false,
      formValidate: {
        teamName: "",
        playerAFile: null,
        playerBFile: null,
        playerAFileName: "",
        playerBFileName: "",
        fileC: "",
        fileD: "",
        group: "A",
      },
      isObscure: true,
      ruleCustom: {
        teamName: [
          {
            required: true,
            validator: teamNameRule,
            trigger: "blur",
            transform(value) {
              return value.trim();
            },
          },
        ],
        playerAFileName: [
          {
            required: true,
            validator: playerAFileNameRule,
            trigger: "change",
            transform(value) {
              return value.trim();
            },
          },
        ],
        playerBFileName: [
          {
            required: true,
            validator: playerBFileNameRule,
            trigger: "change",
            transform(value) {
              return value.trim();
            },
          },
        ],
      },
    };
  },
  methods: {
    async init() {
      try {
        const { data } = await getGameInfo({
          uid: this.userInfo.email,
        });

        if (data && data.status === 100000) {
          const { teamInfo = {}, regStatus } = data.data;
          this.formValidate.teamName = teamInfo.name || "";
          this.isRegistered = !!regStatus;
        } else {
          data.desc && this.$toast.center(data.desc);
        }
      } catch (e) {
        console.log("getGameInfo err", e);
      }
    },
    registerSubmit(name) {
      let that = this;
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("uid", that.userInfo.email);
          formData.append("group", that.formValidate.group);
          formData.append("name", that.formValidate.teamName);
          formData.append("fileA", that.formValidate.playerAFile);
          formData.append("fileB", that.formValidate.playerBFile);
          formData.append(
            "fileC",
            that.isObscure
              ? that.formValidate.fileC
              : that.formValidate.playerAFile
          );
          formData.append(
            "fileD",
            that.isObscure
              ? that.formValidate.fileD
              : that.formValidate.playerBFile
          );

          try {
            const { data } = await registerGame(formData);
            if (data && (data.status === 100000 || data.status === 400)) {
              const { regStatus } = data.data;
              const errMsg = {
                0: "注册成功～",
                1: "您已经注册过了～",
                2: "注册失败，队伍名重复",
                3: "当前组已满员，已自动分配到另一组",
                4: "两组均已满员，注册失败",
              };
              that.$toast(errMsg[regStatus]);
              if (regStatus === 2 || regStatus === 4) {
                that.isRegistered = false;
              } else {
                that.isRegistered = true;
              }
            } else {
              data.desc && that.$toast(data.desc);
            }
          } catch (e) {
            console.log("registerSubmit err", e);
          }
        } else {
          if (!that.formValidate.teamName) {
            this.$toast.center("请输入队名");
          } else if (!that.formValidate.playerAFileName) {
            this.$toast.center("请上传A战队文件");
          } else if (!that.formValidate.playerBFileName) {
            this.$toast.center("请上传B战队文件");
          }
        }
      });
    },
    async cancleRegister() {
      try {
        const { data } = await cancleRegisterGame({
          uid: this.userInfo.email,
        });

        if (data && data.status === 100000) {
          this.$toast.center("取消报名成功");
          this.isRegistered = false;
          this.$refs.formValidate.resetFields();
          this.$refs.playerAFile.value = "";
          this.$refs.playerBFile.value = "";
        } else {
          data.desc && this.$toast.center(data.desc);
        }
      } catch (e) {
        console.log("cancleRegister err", e);
      }
    },
    async updateFile(name) {
      let that = this;
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("uid", that.userInfo.email);
          formData.append("fileA", that.formValidate.playerAFile);
          formData.append("fileB", that.formValidate.playerBFile);
          formData.append(
            "fileC",
            that.isObscure
              ? that.formValidate.fileC
              : that.formValidate.playerAFile
          );
          formData.append(
            "fileD",
            that.isObscure
              ? that.formValidate.fileD
              : that.formValidate.playerBFile
          );

          try {
            const { data } = await updatePlayerFile(formData);
            if (data && data.status === 100000) {
              that.$toast.center("更新文件成功");
            } else {
              data.desc && that.$toast.center(data.desc);
            }
          } catch (e) {
            console.log("updateFile err", e);
          }
        } else {
          if (!that.formValidate.playerAFileName) {
            that.$toast.center("请上传A战队文件");
          } else if (!that.formValidate.playerBFileName) {
            that.$toast.center("请上传B战队文件");
          }
        }
      });
    },
    checkFileType(fileName) {
      // 获取文件扩展名
      var suffixStr = fileName.split(".").pop();
      if (suffixStr !== "js") {
        this.$toast.center("请上传js文件");
        return false;
      }
      return true;
    },
    async changeplayerAFile(e) {
      let file = e.target.files[0];
      if (this.checkFileType(file.name)) {
        this.formValidate.playerAFileName = file.name;
        this.formValidate.playerAFile = file;
        const obscureFile = await this.obscure(file);
        this.formValidate.fileC = obscureFile || file;
      }
    },
    async changeplayerBFile(e) {
      let file = e.target.files[0];
      if (this.checkFileType(file.name)) {
        this.formValidate.playerBFileName = file.name;
        this.formValidate.playerBFile = file;
        const obscureFile = await this.obscure(file);
        this.formValidate.fileD = obscureFile || file;
      }
    },
    toMapPage() {
      this.$router.push({ path: `/tank/map` });
    },
    obscure(file) {
      const reader = new FileReader();
      const _this = this;
      return new Promise((resolve) => {
        reader.onload = function fileReadCompleted() {
          try {
            const res = JavaScriptObfuscator.obfuscate(reader.result, {
              compact: true,
              controlFlowFlattening: false,
              deadCodeInjection: false,
              debugProtection: false,
              debugProtectionInterval: 0,
              disableConsoleOutput: false,
              identifierNamesGenerator: "hexadecimal",
              log: false,
              numbersToExpressions: false,
              renameGlobals: false,
              selfDefending: false,
              simplify: true,
              splitStrings: false,
              stringArray: true,
              stringArrayCallsTransform: false,
              stringArrayCallsTransformThreshold: 0.5,
              stringArrayEncoding: [],
              stringArrayIndexShift: true,
              stringArrayRotate: true,
              stringArrayShuffle: true,
              stringArrayWrappersCount: 1,
              stringArrayWrappersChainedCalls: true,
              stringArrayWrappersParametersMaxCount: 2,
              stringArrayWrappersType: "variable",
              stringArrayThreshold: 0.75,
              unicodeEscapeSequence: true,
            });
            const compactCode = res.getObfuscatedCode();
            const codeBase64 = window.btoa(compactCode);
            const codeBlob = _this.base64toBlob(
              "data:text/javascript;base64," + codeBase64
            );
            const obscureFile = new File([codeBlob], file.name, {
              type: "text/javascript;charset=utf-8",
            });
            resolve(obscureFile);
          } catch (error) {
            alert("混淆失败～");
            resolve("");
          }
        };
        reader.readAsText(file);
      });
    },
    base64toBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    handleSwitchChange() {},
  },
  destroyed() {},
};
</script>
<style lang="scss" scoped>
/deep/.ivu-form-item-error-tip {
  display: none;
}
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow-x: auto;
  background: url(./assets/tank_reg_bg@1x.jpg) no-repeat center center;
  background-size: 100% 100%;
  box-sizing: border-box;
  .img-logo {
    width: 518px;
    height: 10.3%;
    background: url(./assets/ai_normal.png) no-repeat center center;
    background-size: 100%;
    position: absolute;
    top: 7.6%;
    left: 50%;
    transform: translateX(-50%);
  }
  .download-link {
    position: absolute;
    top: -50px;
    left: 0;
    font-size: 20px;
  }
  .blink_me {
    animation: blinker 1s linear infinite;
  }
  @keyframes blinker {
    50% {
      opacity: 0.3;
    }
  }
  .center {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 1200px;
    height: 100%;
    margin: 0 auto;
    overflow-y: auto;
    position: relative;
    font-family: PingFangSC-Regular, PingFang SC;
    .register-form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100%;

      .registered-info {
        // height: 18.52%;
        height: 22%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .tip {
          height: 28%;
          font-size: 40px;
          line-height: 100%;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #00cfe7;
          text-align: center;
        }
        .team-name {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 627px;
          height: 59%;
          background: url("./assets/tank_team_name@2x.png") no-repeat center
            center;
          background-size: 100% 100%;
          font-size: 36px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #ffffff;
          // margin-top: 13%;
          margin-top: 2%;
        }
      }

      /deep/.ivu-form-item {
        margin: 0;
      }
      .input-name {
        width: 970px;
        height: 6.6%;
        border-radius: 13px;
        opacity: 0.7;
        border: 4px solid #00f7ff;
        // margin-bottom: 7.5%;
        /deep/.ivu-input {
          width: 100%;
          height: 100%;
          background: linear-gradient(180deg, #3c2052 0%, #00abc1 100%);
          font-size: 28px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          text-align: center;
          border: 0;
          &::placeholder {
            color: #ffffff;
            font-size: 28px;
          }
        }
      }
      .battle-file {
        margin-top: 7.5%;
        width: 100%;
        height: 23.05%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .option-box {
        position: absolute;
        // display: flex;
        margin-top: 30%;
        &-isRegistered {
          position: absolute;
          // top: 560px;
          margin-top: 35%;
        }
        .select-group,
        .obscure {
          display: flex;
          align-items: center;
          font-size: 30px;
          color: #fff;
          ::v-deep {
            .ivu-radio-group {
              // display: flex;
            }
            .ivu-radio-wrapper {
              display: flex;
              align-items: center;
            }
            .ivu-radio-large.ivu-radio-wrapper {
              font-size: 26px;
              align-items: center;
            }
          }
        }
        .obscure {
          margin-top: 10px;
          font-size: 16px;
          margin-left: 30px;
        }
      }
      .input-player {
        width: 338px;
        height: 100%;
        background: url(./assets/tank_reg_upload@2x.png) no-repeat center center;
        background-size: 100% 100%;
        position: relative;
        /deep/.ivu-form-item-content {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
        }
        input {
          width: 100%;
          height: 100%;
          position: absolute;
          font-size: 100px;
          right: 0;
          top: 0;
          opacity: 0;
          filter: alpha(opacity=0);
          cursor: pointer;
          z-index: 9;
        }
        .add {
          height: 35.74%;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          .add-icon {
            width: 54px;
            height: 60.67%;
            opacity: 0.79;
            background: url(./assets/add_icon@2x.png) no-repeat center center;
            background-size: 100% 100%;
            margin-bottom: 14.6%;
          }
          .text {
            font-size: 16px;
            line-height: 22px;
          }
        }
        .file-name {
          width: 338px;
          position: absolute;
          bottom: -50px;
          left: 50%;
          transform: translateX(-50%);
          height: 16.86%;
          font-size: 24px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          line-height: 100%;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .input-player:first-child {
        margin-right: 296px;
      }
    }
    .reg-btns {
      height: 8.24%;
      margin-top: 8.24%;
      .btn {
        border: none;
        width: 217px;
        height: 100%;
        background: url(./assets/tank_reg_btn@2x.png) no-repeat center center;
        background-size: 100% 100%;
        cursor: pointer;
        font-size: 24px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 100%;
      }
      .register-submit {
        transform: translateY(80px);
      }
    }
    .update-file {
      // margin-right: 220px;
    }
    /deep/.ivu-form-item-content {
      margin: 0 !important;
    }
    .map-entrance {
      width: 200px;
      height: 4.16%;
      position: absolute;
      top: 7.74%;
      right: 54px;
      cursor: pointer;
      background: url(./assets/map_enter.gif) no-repeat center center;
      background-size: 100% 100%;
    }
  }
}
</style>
